package com.uduemc.biso.node.web.component.html;

import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.uduemc.biso.node.core.common.entities.SiteLogo;
import com.uduemc.biso.node.core.common.udinpojo.LogoData;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.entities.SLogo;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.core.utils.ComponentUtil;
import com.uduemc.biso.node.web.component.SiteUrlComponent;

@Component
public class HLogoUdin {

	private static String name = "logo";

	@Autowired
	private BasicUdin basicUdin;

	@Autowired
	private SiteUrlComponent siteUrlComponent;

	public StringBuilder html(SiteLogo siteLogo) {
		if (siteLogo == null || siteLogo.getLogo() == null) {
			return new StringBuilder();
		}
		// {"fontSize":"1em","color":"#40FFCC","fontWeight":"bolder"}
		SLogo logo = siteLogo.getLogo();
		Short type = logo.getType();
		if (type == null || type.shortValue() == (short) 0) {
			return new StringBuilder("<!-- logo empty -->\n");
		}
		RepertoryQuote repertoryQuote = siteLogo.getRepertoryQuote();
		String config = logo.getConfig();
		LogoData logoConfig = null;
		if (StringUtils.hasText(config)) {
			logoConfig = ComponentUtil.getConfig(config, LogoData.class);
		}

		String style = logoConfig == null ? "" : ComponentUtil.getStyle(logoConfig.getConfig());

		VelocityContext ctx = new VelocityContext();
		// 显示文字还是显示图片
		ctx.put("type", logo.getType());
		ctx.put("style", style);
		ctx.put("title", logo.getTitle());

		String src = siteUrlComponent.getImgEmptySrc();
		HRepertory hRepertory = repertoryQuote != null ? repertoryQuote.getHRepertory() : null;
		if (hRepertory != null) {
			src = siteUrlComponent.getImgSrc(hRepertory);
		}
		ctx.put("imgSrc", src);
		ctx.put("imgAlt", logoConfig != null && logoConfig.getImg() != null ? logoConfig.getImg().getAlt() : "");
		ctx.put("imgTitle", logoConfig != null && logoConfig.getImg() != null ? logoConfig.getImg().getTitle() : "");
		ctx.put("href", siteUrlComponent.getLogoHref());

		Template t = getTemplate("default");
		StringWriter sw = new StringWriter();
		t.merge(ctx, sw);

		return new StringBuilder("<!-- logo -->\n" + sw.toString());
	}

	public Template getTemplate(String theme) {
		return basicUdin.getTemplate(name, theme);
	}

}
